const fs = require("fs");
const Sequelize = require("sequelize");
const path = require('path');

module.exports = dbPath => {
    const sequelize = new Sequelize('database', null, null, {
        dialect: "sqlite",
        storage: dbPath,
        pool: {
            max: 10,
            min: 0,
            idle: 10000
        },
        logging: false,
        define: {
            timestamps: false, // true by default，设置true会添加createdAt和updatedAt两个字段
            freezeTableName: true, //表名和定义的model名一样
            underscored: true, //不要使用驼峰命名
        }
    });
    const db = {};
    fs
        .readdirSync(__dirname)
        .filter(function(file) {
            return (file.indexOf(".") !== 0) && (file !== "index.js");
        })
        .forEach(function(file) {
            let model = sequelize.import(path.join(__dirname, file));
            db[model.name] = model;
        });

    Object.keys(db).forEach(function(modelName) {
        if ("associate" in db[modelName]) {
            db[modelName].associate(db);
        }
    });

    db.sequelize = sequelize;
    db.Sequelize = Sequelize;
    return db;
}